package controllers

import (
	"encoding/json"
	"strconv"
	"strings"

	"assist-server/models"
	"github.com/astaxie/beego"
)

// Operations about Users
type LoginController struct {
	beego.Controller
}

// @Title CreateUser
// @Description create users
// @Param	body		body 	models.UserInfo	true		"body for user content"
// @Success 200 {int} models.User.Id
// @Failure 403 body is empty
// @router / [post]
func (l *LoginController) Post() {
	var user models.UserInfo
	var login models.TLogLogin
	var msgServer models.GameInfo

	// 解析登录消息
	err := json.Unmarshal(l.Ctx.Input.RequestBody, &user)
	if err != nil {
		beego.Error("Login: json err = ", err)
	} else {
		beego.Info("Login: json data = ", user)

		flag := false
		ver := strings.Split(user.Version, ".")
		newVer := strings.Split(beego.AppConfig.String("version"), ".")

		if len(ver) < len(newVer) {
			for i := 0; i < 3-len(ver); i++ {
				ver = append(ver, "0")
			}
		}
		for k, v := range newVer {
			beego.Info("Login: data === ", ver, newVer)
			newvv, _ := strconv.Atoi(v)
			vv, _ := strconv.Atoi(ver[k])
			if vv < newvv {
				flag = true
				break
			}
		}

		if flag {
			msg := models.MsgInfo{
				Code: 500,
				Msg:  "版本过低请升级客户端！",
			}
			l.Data["json"] = msg
		} else {
			// 创建账号
			uin := models.GetAccount(user)

			if uin > 0 {
				// 获取ip、openid
				login.OpIp = l.Ctx.Input.IP()
				login.GeoPoint = user.GeoPoint
				login.Uin = uin

				login.Session = models.CreateSession(login)

				// 记录登录日志
				models.LogLogin(login)

				base, _ := beego.AppConfig.Int("baseNum")
				msgServer.UserId = int(uin) + base
				msgServer.Server = beego.AppConfig.String("gameserver")
				msgServer.Port = beego.AppConfig.String("gameport")
				msgServer.Sex = user.Sex
				msgServer.Session = login.Session

				l.Data["json"] = msgServer
			}
		}

		l.ServeJSON()
	}
}
